//! INSERT语句功能测试
//!
//! 测试SQL解析器和执行引擎对INSERT语句的完整支持

use cdb::{Result, config::DatabaseConfig, sql::QueryEngine, storage::StorageEngine};
use std::sync::Arc;
use parking_lot::RwLock;
use tempfile::TempDir;

#[test]
fn test_insert_parsing() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 首先创建表
    let create_table_sql = r#"
        CREATE TABLE users (
            id INTEGER PRIMARY KEY,
            name VARCHAR(100) NOT NULL,
            age INTEGER,
            email VARCHAR(255)
        )
    "#;
    
    let create_result = query_engine.execute(create_table_sql)?;
    assert_eq!(create_result.get_affected_rows(), 1);

    // 测试基础INSERT语句解析
    let insert_sql = r#"
        INSERT INTO users (id, name, age, email) 
        VALUES (1, 'Alice', 25, 'alice@example.com')
    "#;

    // 测试解析是否成功
    let explain_result = query_engine.explain(insert_sql)?;
    
    // 验证解释结果包含Insert相关信息
    assert!(explain_result.contains("Insert") || explain_result.contains("INSERT"));
    assert!(explain_result.contains("users"));
    
    println!("✅ INSERT语句解析测试通过");
    println!("执行计划:\n{}", explain_result);
    Ok(())
}

#[test]
fn test_insert_execution() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 首先创建表
    let create_table_sql = r#"
        CREATE TABLE test_insert (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            score REAL
        )
    "#;
    
    let create_result = query_engine.execute(create_table_sql)?;
    assert_eq!(create_result.get_affected_rows(), 1);

    // 测试INSERT语句执行
    let insert_sql = r#"
        INSERT INTO test_insert (id, name, score) 
        VALUES (1, 'Test User', 95.5)
    "#;

    let result = query_engine.execute(insert_sql)?;
    
    // 验证结果
    assert_eq!(result.get_affected_rows(), 1);
    assert_eq!(result.rows().len(), 0); // INSERT不返回数据行
    
    println!("✅ INSERT语句执行测试通过");
    Ok(())
}

#[test]
fn test_multiple_inserts() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 首先创建表
    let create_table_sql = r#"
        CREATE TABLE products (
            id INTEGER PRIMARY KEY,
            name VARCHAR(100),
            price REAL,
            in_stock BOOLEAN
        )
    "#;
    
    let create_result = query_engine.execute(create_table_sql)?;
    assert_eq!(create_result.get_affected_rows(), 1);

    // 测试多条INSERT语句
    let insert_sqls = vec![
        "INSERT INTO products (id, name, price, in_stock) VALUES (1, 'Laptop', 999.99, true)",
        "INSERT INTO products (id, name, price, in_stock) VALUES (2, 'Mouse', 29.99, true)",
        "INSERT INTO products (id, name, price, in_stock) VALUES (3, 'Keyboard', 79.99, false)",
    ];

    for (i, sql) in insert_sqls.iter().enumerate() {
        let result = query_engine.execute(sql)?;
        assert_eq!(result.get_affected_rows(), 1);
        println!("✅ 第{}条INSERT语句执行成功", i + 1);
    }
    
    println!("✅ 多条INSERT语句测试通过");
    Ok(())
}

#[test]
fn test_insert_with_different_data_types() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 创建包含多种数据类型的表
    let create_table_sql = r#"
        CREATE TABLE data_types_test (
            id INTEGER PRIMARY KEY,
            name TEXT,
            score REAL,
            is_active BOOLEAN,
            description VARCHAR(500)
        )
    "#;
    
    let create_result = query_engine.execute(create_table_sql)?;
    assert_eq!(create_result.get_affected_rows(), 1);

    // 测试不同数据类型的INSERT
    let insert_sql = r#"
        INSERT INTO data_types_test (id, name, score, is_active, description) 
        VALUES (1, 'Test Record', 88.5, true, 'This is a test description')
    "#;

    let result = query_engine.execute(insert_sql)?;
    assert_eq!(result.get_affected_rows(), 1);
    
    println!("✅ 不同数据类型的INSERT测试通过");
    Ok(())
}

#[test]
fn test_insert_performance() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 创建表
    let create_table_sql = r#"
        CREATE TABLE performance_test (
            id INTEGER PRIMARY KEY,
            data VARCHAR(100)
        )
    "#;
    
    let create_result = query_engine.execute(create_table_sql)?;
    assert_eq!(create_result.get_affected_rows(), 1);

    let start_time = std::time::Instant::now();

    // 插入多条记录测试性能
    for i in 1..=10 {
        let sql = format!(
            "INSERT INTO performance_test (id, data) VALUES ({}, 'Test data {}')",
            i, i
        );

        let result = query_engine.execute(&sql)?;
        assert_eq!(result.get_affected_rows(), 1);
    }

    let elapsed = start_time.elapsed();
    println!("✅ INSERT性能测试通过");
    println!("插入10条记录耗时: {:?}", elapsed);
    println!("平均每条记录: {:?}", elapsed / 10);

    // 验证性能要求（每条记录插入应该在50ms以内）
    assert!(elapsed.as_millis() < 500, "INSERT性能不达标");

    Ok(())
}

#[test]
fn test_insert_error_handling() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试插入到不存在的表
    let insert_sql = "INSERT INTO non_existent_table (id, name) VALUES (1, 'test')";
    
    let result = query_engine.execute(insert_sql);
    assert!(result.is_err(), "应该返回错误：表不存在");
    
    println!("✅ INSERT错误处理测试通过");
    Ok(())
}
